package com.zlq.cn.interceptor;


import com.zlq.cn.api.ApiResult;
import com.zlq.cn.api.ResponseException;
import one.util.streamex.StreamEx;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.UndeclaredThrowableException;

@RestControllerAdvice
public class ApiExceptionHandler {
    protected Logger logger = LoggerFactory.getLogger(getClass().getName());

    @ExceptionHandler(value = Throwable.class)
    public Object handleServiceException(Throwable e, HttpServletRequest request, HttpServletResponse response) {
        logger.info("捕获到异常", e);
        if (e instanceof UndeclaredThrowableException) {
            return ApiResult.resultError(((UndeclaredThrowableException) e).getUndeclaredThrowable().getMessage());
        } else if (e instanceof InvocationTargetException) {
            return ApiResult.resultError(((InvocationTargetException) e).getTargetException().getMessage());
        }
        return ApiResult.resultError(e.getMessage());
    }

    @ExceptionHandler(value = MethodArgumentNotValidException.class)
    public Object handleServiceException(MethodArgumentNotValidException e, HttpServletRequest request, HttpServletResponse response) {
        String errorMsg = StreamEx.of(e.getBindingResult().getAllErrors())
                .map(ObjectError::getDefaultMessage)
                .joining("\n");
        return ApiResult.resultError(errorMsg);
    }

    @ExceptionHandler(value = ResponseException.class)
    public Object handleResponseException(ResponseException responseException, HttpServletRequest request, HttpServletResponse response) {
        return ApiResult.resultError(responseException);
    }

}
